package controllers;

import models.*;
import play.data.Form;
import play.mvc.*;
import views.html.edit;

public class Types extends Controller {

	static Form<Type> typeForm = form(Type.class);

	public static Result types() {
		return ok(
				views.html.types.render(null,Type.all(), typeForm));
	}

	public static Result add() {
		Form<Type> filledForm = typeForm.bindFromRequest();
		if(filledForm.hasErrors()) {
			flash("error","OOOooops!!! Remplir les champs manquants.");
			return badRequest(
					views.html.types.render(null,Type.all(), filledForm));
		}else { // <--- on n'enregistre que si tout va bien
			final Type _type = typeForm.bindFromRequest().get();
			if(allType(_type.nType)==null){
				Type.create(_type); 
				flash("success", "Le type ### "
						+ filledForm.get().nType + " ### has been created");				
			}
			else{
				flash("error","OOOooops!!! Le type "
						+ filledForm.get().nType + " est déjà contenu dans la table");
			}
			return redirect(routes.Types.types());  
		}
	}

	private static Type allType(String label) {
		// TODO Auto-generated method stub
		return Type.findNom.where().eq("nType",label).findUnique();
	}

	public static Result deleteType(Long id) {
		Type.delete(id);
		return redirect(routes.Types.types());  
	}

	public static Result editType(Long id){
		if(id==0){
			flash("error","OOOooops!!! Ce produit ne possède pas de type, créer un nouveau type.");
			return redirect(routes.Types.types());  
		}
		else{
			Form<Type> computerForm = form(Type.class).fill(
					Type.find.byId(id)
					);
			return ok(
					edit.render(id, computerForm)
					);
		}
	}

	public static Result update(Long id) {

		Form<Type> editForm = form(Type.class).bindFromRequest();
		if(editForm.hasErrors()) {
			return badRequest(views.html.edit.render(id,editForm));
		}
		editForm.get().update(id);
		flash("success", "Computer " + editForm.get().nType + " has been updated");
		return redirect(routes.Types.types());  
	}	
}
